import lib
import agent
import win
import threading

webBrowerAgent = agent.BrowerAgent()

# 共享变量
shared_processFlag = 1


def listenCommand(name):
    print(name)
    broker_address = "39.98.199.68"
    subscriber = lib.MQTTSubscriber(broker_address, client_id="my_client_id")
    subscriber.setAgentFuncCall(callAgent)
    subscriber.subscribe(topic="topic/webrobot", qos=1)


def callAgent(msgcommand):
    global shared_processFlag
    if shared_processFlag == 1 and  msgcommand['type']=='command':
        commandList = msgcommand['data']
        for cmd in commandList:
            if "action" in cmd:
                print(cmd['action'], cmd['object'])
                if cmd['action'] == "打开":
                    print("执行打开动作.....")
                    webBrowerAgent.open(cmd['object'])
            else:
                print("缺少动作:"+cmd)
    else:
        print("停止处理指令....")
        print(msgcommand)


thread = threading.Thread(target=listenCommand, args=("Thread",))


def startListening():
    global shared_processFlag
    shared_processFlag == 1
    if not thread.is_alive():
        thread.start()


def stopListening():
    global shared_processFlag
    shared_processFlag == 0


if __name__ == "__main__":
    pystray = win.WinPystray()
    pystray.start(startListening, stopListening)
